/**
 * @Date 07-11-2013
 * Class used to get node details from XML file
 */
package com.globalblue.xml;

import java.io.File;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLParser {
	/**
	 * used to get the first node matching expression from a XML document
	 * 
	 * @param filePath
	 * @param expression
	 * @return
	 */
	public Node getNode(String filePath, String expression) {
		try {
			NodeList nodeList = getNodeList(filePath, expression);
			return nodeList.item(0);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * used to get all the nodes matching an expression from a XML file
	 * 
	 * @param filePath
	 * @param expression
	 * @return
	 * @throws Exception
	 */
	public NodeList getNodeList(String filePath, String expression) throws Exception {
		FileInputStream file = new FileInputStream(new File(filePath));

		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

		DocumentBuilder builder = builderFactory.newDocumentBuilder();

		Document xmlDocument = builder.parse(file);
		XPath xPath = XPathFactory.newInstance().newXPath();
		NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
		return nodeList;
	}

	/**
	 * get the matching child node from provided parent node
	 * 
	 * @param parentNode
	 * @param expression
	 * @return
	 * @throws Exception
	 */
	public Node getChildNode(Node parentNode, String expression) throws Exception {
		XPath xPath = XPathFactory.newInstance().newXPath();
		Node node = (Node) xPath.evaluate(expression, parentNode, XPathConstants.NODE);
		return node;
	}
}
